import Vue from 'vue';
export default {
    onLaunch: function(options) {
        let _this = this;
        _this.globalData.options = options;
        uni.setStorageSync('tabIndex', 0);
        console.log("app onLaunch");
        if (!Vue.prototype.$isH5) {
            uni.setKeepScreenOn({
                keepScreenOn: true
            });
        }
        if (Vue.prototype.$isMpWeixin) {
            // 小程序检测更新
            if (options.scene != 1154) {
                _this.checkWxmpUpdate();
            }
            uni.setStorageSync('login_page', '/packageA/pages/user/mplogin');
        }

        if (Vue.prototype.$isAppPlus) {
            uni.setStorageSync('login_page', '/packageA/pages/user/applogin');
            if (uni.getSystemInfoSync().platform == 'android') {
                _this.$downloader.init({
                        maxDownloadTasks: 3, // 最大同时下载任务数
                        maxDownloadThreads: 3, // 最大下载线程数
                        autoRecovery: false, // 是否自动恢复下载
                        openRetry: true, // 下载失败是否打开重试
                        maxRetryCount: 2, // 重试次数
                        retryIntervalMillis: 1000 // 每次重试时间间隔（毫秒）
                    },
                    function(res) {
                        if (0 == res.code) {
                            // console.log('下载插件' + res.msg);
                        }
                    }
                );
            }
        }
        const context = _this;
        _this.globalData._i18n = _this.$i18n;
        _this.globalData.$t = function(str) {
            return context.$t(str);
        };
    },
    onShow: function(e) {
        console.log("app onShow");
        let _this = this;
        _this.addEventListenerClipboard(_this);

        if (Vue.prototype.$isMpWeixin) {
            // 监听截图
            uni.onUserCaptureScreen(function() {
                let routes = getCurrentPages();
                let curRoute = routes[routes.length - 1].route;
                let data = {
                    type: 1,
                    page: curRoute
                };
                _this.behaviorLog(data);
            });
        }


        uni.removeStorageSync('tabtarIndex');
        _this.getCommonSetting();
    },
    onHide: function() {

    },
    methods: {
        logHistory(videoInfo) {
            let historyList = uni.getStorageSync('historyList') || [];
            let save = {
                img: videoInfo.vod_pic,
                title: videoInfo.title,
                id: videoInfo.vod_id,
                index: videoInfo.index,
                type: videoInfo.type
            };
            //看是否有相同项，有相同项则不保存
            let oldHave = false;
            let findIndex = -1;
            historyList.forEach((v, k) => {
                if (v.id == videoInfo.vod_id) {
                    oldHave = true;
                    findIndex = k;
                }
            });
            if (!oldHave) {
                historyList.unshift(save);
            } else {
                historyList.splice(findIndex, 1);
                historyList.unshift(save);
            }
            uni.setStorageSync('historyList', historyList);
        },
        getCommonSetting() {
            let _this = this;
            try {
                // 全局配置
                _this.$http
                    .post('/videos/config/getConfig', {})
                    .then(res => {
                        if (!res.data && !uni.getStorageSync('sys_config')) {
                            uni.showModal({
                                title: '提示',
                                content: '网络繁忙，请重试',
                                showCancel: false,
                                success() {
                                    uni.reLaunch({
                                        url: '/pages/index/index'
                                    })
                                }
                            })
                            return false;
                        }
                        uni.setStorageSync('sys_config', res.data);
                        _this.sys_config = res.data;
                        _this.globalData.adSwitchKg = res.data.ad_switch;
                        // 会员无广告
                        if (res.data.no_ad_limit > 0 && res.data.userinfo && res.data.no_ad_limit_arr && res.data
                            .no_ad_limit_arr.indexOf(
                                res.data.userinfo.group_id) != -1) {
                            _this.globalData.adSwitchKg = 0;
                        }
                        // 中心审核状态
                        if (res.data.show_xx == 0 && res.data.member_group_switch && res.data.userinfo && res.data
                            .userinfo.group_id >= res.data.member_group_limit) {
                            _this.globalData.centerShowxx = false;
                        }
                    })
                    .then(v => {
                        _this.menuInit();
                    })
            } catch (e) {
                _this.getCommonSetting();
            }
        },
        menuInit() {
            // 底部导航
            let language = uni.getStorageSync('language'),
                _this = this,
                local_menu = uni.getStorageSync('menuList');
            language = language ? language : 'zh';

            let now_timestamp = Date.parse(new Date()) / 1000;

            if (local_menu && now_timestamp < local_menu.exp_time) {
                _this.globalData.tarbarObj.tarbarList = local_menu.menu;
                _this.initLanguage();
                return true;
            }
            _this.$http.post('/tabbar/menu/getMenus', {}).then(res => {
                if (res.code == 200) {
                    _this.globalData.tarbarObj.tarbarList = [];
                    res.data.list.forEach((v, k) => {
                        if (v.status) {
                            if (v.is_default == 1 && _this.sys_config.tarbar_up == 1) {
                                _this.globalData.tarbarObj.midButton = true;
                                _this.globalData.tarbarObj.tarbarList.push({
                                    iconPath: _this.$config.apiImageUrl + v.icon,
                                    selectedIconPath: _this.$config.apiImageUrl + v.active_icon,
                                    text: language != 'zh' ? v.nav_alias : v.nav_name,
                                    customIcon: false,
                                    midButton: true,
                                    pagePath: v.jump_url,
                                    isDefault: v.is_default
                                });
                            } else {
                                _this.globalData.tarbarObj.tarbarList.push({
                                    iconPath: _this.$config.apiImageUrl + v.icon,
                                    selectedIconPath: _this.$config.apiImageUrl + v.active_icon,
                                    text: language != 'zh' ? v.nav_alias : v.nav_name,
                                    customIcon: false,
                                    midButton: false,
                                    pagePath: v.jump_url,
                                    isDefault: v.is_default
                                });
                            }
                        }
                    });
                    uni.setStorageSync('menuList', {
                        exptime: Date.parse(new Date()) / 1000 + 600,
                        menu: _this.globalData.tarbarObj.tarbarList
                    });
                    _this.initLanguage();
                } else {
                    uni.showToast({
                        title: 'Ok Ծ‸ Ծ ',
                        icon: 'none'
                    });
                }
            }).then(v => {
                _this.getAdlist();
            });
        },
        checkWxmpUpdate(isClick = false) {
            var _this = this;
            if (uni.canIUse('getUpdateManager')) {
                const updateManager = uni.getUpdateManager();
                if (isClick) {
                    uni.showLoading({
                        mask: true
                    })
                }
                updateManager.onCheckForUpdate(function(res) {
                    if (isClick) {
                        uni.hideLoading();
                    }
                    if (res.hasUpdate) {
                        uni.showModal({
                            title: '更新提示',
                            showCancel: false,
                            confirmText: '确定更新',
                            content: '检测到新版本，是否下载新版本并重启小程序？',
                            success: function(res) {
                                if (res.confirm) {
                                    _this.downLoadAndUpdate(updateManager);
                                } else if (res.cancel) {
                                    uni.showModal({
                                        title: '温馨提示',
                                        content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦',
                                        showCancel: false,
                                        confirmText: '确定更新',
                                        success: function(res) {
                                            if (res.confirm) {
                                                //下载新版本，并重新应用
                                                _this.downLoadAndUpdate(updateManager);
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    } else {
                        if (isClick) {
                            uni.showModal({
                                title: '温馨提示',
                                content: '当前已是最新版本',
                                showCancel: false,
                                confirmText: '确定'
                            });
                        }
                    }
                });
            } else {
                uni.showModal({
                    title: '提示',
                    content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
                });
            }
        },
        downLoadAndUpdate: function(updateManager) {
            var self = this;
            wx.showLoading();
            //静默下载更新小程序新版本
            updateManager.onUpdateReady(function() {
                wx.hideLoading();
                //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
            });
            updateManager.onUpdateFailed(function() {
                // 新的版本下载失败
                wx.showModal({
                    title: '新版本提示',
                    content: '新版本已经上线啦，请您删除当前小程序，重新搜索打开'
                });
            });
        },
        getOneAd(type) {
            type = type ? type : 'common_ad';
            let tmpAdlist = uni.getStorageSync('adInfo');
            if (tmpAdlist && tmpAdlist[type].length > 0) {
                let num = parseInt(Math.random() * (tmpAdlist[type].length - 1 + 1), 10);
                return tmpAdlist[type][num];
            }
            return '';
        },
        getAdlist() {
            let _this = this,
                tmpAdlist = [];
            _this.$http.post('/videos/home/getAdList', {}).then(res => {
                let data = res.data;
                if (Vue.prototype.$isMp) {
                    tmpAdlist = data;
                } else {
                    tmpAdlist = data;
                    // let tmp = [];
                    // data.forEach((v, k) => {
                    //     if (v.ad_type < 3) {
                    //         tmp.push(data[k]);
                    //     }
                    // });
                    // tmpAdlist = tmp;
                }
                uni.setStorageSync('adInfo', tmpAdlist);
            });
        },
        checkLogin(goLogin, success, error) {
            let userInfo = uni.getStorageSync('userInfo');
            if (!userInfo) {
                if (goLogin) {
                    let routes = getCurrentPages();
                    let curRoute = routes[routes.length - 1].route;
                    let curParam = routes[routes.length - 1].options;
                    let share_scene = [1007, 1008, 1010, 1011, 1012, 1013, 1014, 1036, 1047, 1048, 1049, 1058, 1074,
                        1082, 1096
                    ];
                    if (share_scene.indexOf(this.globalData.options.scene) != -1) {
                        let param = Vue.prototype.$u.queryParams(curParam);
                        if (param.indexOf('froms') == -1) {
                            if (param.indexOf('?') == -1) {
                                uni.setStorageSync('from_page', '/' + curRoute + param + '?froms=1');
                            } else {
                                uni.setStorageSync('from_page', '/' + curRoute + param + '&froms=1');
                            }
                        } else {
                            uni.setStorageSync('from_page', '/' + curRoute + param);
                        }
                    } else {
                        uni.setStorageSync('from_page', '/' + curRoute + Vue.prototype.$u.queryParams(curParam));
                    }
                    if (Vue.prototype.$isMp) {
                        uni.navigateTo({
                            url: '/packageA/pages/user/mplogin'
                        });
                    } else {
                        uni.navigateTo({
                            url: '/packageA/pages/user/applogin'
                        });
                    }
                } else {
                    error && error();
                    return false;
                }
            } else {
                success && success(userInfo);
                return userInfo;
            }
        },
        initLanguage() {
            // 设置首页tab默认语言
            this.globalData.typelist.forEach((v, k) => {
                this.globalData.typelist[k].name = this.globalData.$t('typeList')[k];
            });
        },
        // 为以后多语言选择留坑
        changeLang(lang = 'zh') {
            let _this = this;
            // model层提示切换
            let language = uni.getStorageSync('language');
            let title = language == 'en' ? 'Hey' : '提示';
            let content = language == 'en' ? 'Do you want to change the software language?' : '是否要切换当前软件语言？';
            let cancelText = language == 'en' ? 'Cancel' : '取消';
            let confirmText = language == 'en' ? 'Ok' : '确定';
            uni.showModal({
                title: title,
                content: content,
                cancelText: cancelText,
                confirmText: confirmText,
                success: function(res) {
                    if (res.confirm) {
                        switch (language) {
                            case 'en':
                                language = 'zh';
                                break;
                            case 'zh':
                                language = 'en';
                                break;
                            default:
                                language = 'zh';
                                break;
                        }
                        uni.setStorageSync('language', language);
                        // 提示重新打开应用
                        _this.reOpen(language);
                    }
                }
            });
        },
        reOpen(language) {
            let content = '',
                confirmText = '',
                title = '';
            if (Vue.prototype.$isAppPlus) {
                switch (language) {
                    case 'en':
                        title = 'Tips';
                        content = 'The language is changed, please reopen the app';
                        confirmText = 'Ok';
                        break;
                    case 'zh':
                        title = '提示';
                        content = '切换语言成功，请重新打开应用';
                        confirmText = '确定';
                        break;
                }
                uni.showModal({
                    title: title,
                    content: content,
                    showCancel: false,
                    confirmText: confirmText,
                    success() {
                        _this.globalData._i18n.locale = language;
                        plus.runtime.quit();
                    }
                });
            }
            if (Vue.prototype.$isMp) {
                switch (language) {
                    case 'en':
                        title = 'Tips';
                        content =
                            'The language is changed, please click the upper right corner (·•·) to re-enter the applet';
                        confirmText = 'Ok';
                        break;
                    case 'zh':
                        title = '提示';
                        content = '切换语言成功，请点击右上角(·•·)重新进入小程序';
                        confirmText = '确定';
                        break;
                }
                uni.showModal({
                    title: title,
                    content: content,
                    showCancel: false,
                    confirmText: confirmText,
                    success() {}
                });
            }
        },
        showLoading(refs, callback, timeOut) {
            if (!Vue.prototype.$isAppPlus) {
                refs.open();
                setTimeout(callback || function() {}, timeOut || 300);
            } else {
                uni.showLoading({
                    title: '',
                    mask: true,
                    success() {
                        callback || function() {};
                    }
                });
            }
        },
        closeLoading(refs, callback, timeOut) {
            if (!Vue.prototype.$isAppPlus) {
                refs.close();
                setTimeout(callback || function() {}, timeOut || 300);
            } else {
                uni.hideLoading();
            }
        },
        godetail(vod_id) {
            if (Vue.prototype.$isAppPlus) {
                if (Vue.prototype.$u.os() == 'android') {
                    uni.navigateTo({
                        url: '../../pages/app/index?id=' + vod_id
                    });
                } else {
                    uni.navigateTo({
                        url: '../../pages/ios/index?id=' + vod_id
                    });
                }
            }
            if (Vue.prototype.$isMpWeixin) {
                let sys = uni.getStorageSync('sys_config');
                // 如果用户已登录，后台开了，并且模版id配置了
                if (sys && sys.userinfo.hasOwnProperty('id') && sys.wxmp_tpl_switch && sys.template_id) {
                    // 是否已过期
                    let timeout = uni.getStorageSync('tpl_alert_time');
                    let now_timestamp = Date.parse(new Date()) / 1000;
                    if (timeout && now_timestamp < timeout) {
                        uni.navigateTo({
                            url: '/packageA/pages/detail/index?id=' + vod_id
                        });
                    } else {
                        uni.showLoading({
                            title: 'Loading...',
                            mask: true
                        })
                        setTimeout((v) => {
                            uni.hideLoading();
                        }, 500)
                        let tpl = [];
                        tpl.push(sys.template_id);
                        uni.requestSubscribeMessage({
                            tmplIds: tpl,
                            complete(res) {
                                uni.setStorageSync('tpl_alert_time', (Date.parse(new Date()) / 1000) + (sys
                                    .wxmp_tpl_Interval * 60));
                                uni.navigateTo({
                                    url: '/packageA/pages/detail/index?id=' + vod_id
                                });
                            }
                        })
                    }
                } else {
                    uni.navigateTo({
                        url: '/packageA/pages/detail/index?id=' + vod_id
                    });
                }
            }
            if (Vue.prototype.$isH5) {
                uni.navigateTo({
                    url: '/pages/webview/h5?id=' + vod_id
                });
            }
        },
        addEventListenerClipboard(_this, callback) {
            _this.$http.post('/videos/config/getConfig', {}).then(res => {
                let sys = res.data;
                if (sys) {
                    // 如果没登陆 不走剪贴板
                    if (!sys.userinfo.hasOwnProperty('id')) {
                        callback && callback(2);
                        return false;
                    }

                    // 如果开了审核 切当前登录会员组已有权限 不走剪贴板
                    if (sys.show_xx && sys.member_group_switch && sys.userinfo.group_id >= sys
                        .member_group_limit) {
                        callback && callback(2);
                        return false;
                    }

                    // 如果已登录 有权限 不走剪贴板
                    if (sys.userinfo.group_id > sys.member_group_limit) {
                        callback && callback(2);
                        return false;
                    }

                    uni.getClipboardData({
                        success: function(res) {
                            uni.hideToast();
                            if (res.data.indexOf(sys.code_key) != -1) {
                                let c = res.data.replace(/\s/g, " ").replace(/<\/?.+?>/g, " ")
                                    .replace(/[\r\n]/g, " ").replace(
                                        /(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+/,
                                        " ").match(/[A-Za-z0-9]{12}/);
                                if (c) {
                                    uni.showModal({
                                        title: '提示',
                                        content: '检测到您似乎复制了兑换码，是否前往兑换？',
                                        success(res) {
                                            if (res.confirm) {
                                                callback && callback(1);
                                                uni.navigateTo({
                                                    url: '/packageA/pages/user/child/giftCode?code=' +
                                                        c[0]
                                                });
                                            } else {
                                                callback && callback(2);
                                            }
                                        }
                                    });
                                } else {
                                    callback && callback(2);
                                }
                            } else {
                                callback && callback(2);
                            }
                        }
                    });
                } else {
                    callback && callback(2);
                }
            });
        },
        goHome() {
            let path = '/pages/index/index';
            this.globalData.tarbarObj.tarbarList.forEach((v, k) => {
                if (v.isDefault == 1) {
                    path = v.pagePath;
                }
            });
            uni.reLaunch({
                url: path
            });
        },
        behaviorLog(data) {
            let _this = this;
            try {
                let sys = uni.getStorageSync('sys_config');
                // 只有用户是可观看状态时记录
                if (sys && sys.member_group_switch && sys.userinfo && sys
                    .userinfo.group_id >= sys.member_group_limit) {
                    _this.$http.post('/user/behavior/logs', data ? data : {});
                }
            } catch (e) {
                console.log(e);
            }
        }
    }
};
